import React from "react";
import routeWithUserSession from "@/components/ApplicationArea/routeWithUserSession";
import { BrowserRouter as Router, Link } from 'react-router-dom';//
import Layout from "antd/lib/layout";
import Button from "antd/lib/button";
import Col from "antd/lib/col";
import Menu from "antd/lib/menu";
import Divider from "antd/lib/divider";
import Dropdown from "antd/lib/dropdown";
import Row from "antd/lib/row";
import Table from "antd/lib/table";
import ConfigProvider from "antd/lib/config-provider";
import AutoComplete from "antd/lib/auto-complete";
import zhCN from 'antd/es/locale/zh_CN';
import Workflow from "@/services/workflow";
import { createBrowserHistory } from 'history'
import notification from "@/services/notification";
import { currentUser } from "@/services/auth";
import routes from "@/services/routes";
import moment from "moment";
import { AppstoreFilled, DownOutlined, UpOutlined } from "@ant-design/icons";
import QueryShowField from "@/services/queryshowfield";
import CreateQueryShowFieldDialog from "@/components/enums/QueryShowFieldDialog";
const customHistory = createBrowserHistory();

class WorkFlowCheckList extends React.Component {
  state = {
    page: 1,
    pagesize: localStorage.getItem("workflowchecklistpagesize") ? (localStorage.getItem("workflowchecklistpagesize") !== undefined ? Number(localStorage.getItem("workflowchecklistpagesize")) : 20) : 20,
    total: 15,
    loading: false,
    data: [],
    selectedTitle: '',
    code: '',
    name: '',
    tablename: '',
    seltype: "1",
    showall: false,
    queryshowfielddata: [],
  };
  componentWillMount() {
    this.fieldsshowload();
    let param = {
      page: this.state.page,
      pagesize: this.state.pagesize,
      seltype: this.props.seltype,
      userid: currentUser.id,
      code: this.state.code,
      name: this.state.name,
      tablename: this.state.tablename,
    }
    this.fetch(param);
  }
  fetch = (params = {}) => {
    this.setState({ loading: true });
    Workflow.getchecklist(params).then(data => {
      this.setState({
        loading: false,
        data: data.data,
        page: params.page,
        pagesize: params.pagesize,
        total: data.total,
        seltype: params.seltype,
      });
    });
  };
  fieldsshowload = () => {
    QueryShowField.getbycode("workflowchecklist").then(data => {
      this.setState({
        queryshowfielddata: data,
      });
    });
  }
  handlesel = () => {
    let param = {
      page: 1,
      pagesize: this.state.pagesize,
      seltype: this.state.seltype,
      userid: currentUser.id,
      code: this.state.code,
      name: this.state.name,
      tablename: this.state.tablename,
    }
    this.fetch(param);
  };
  handleTableChange = (pagination, filters, sorter) => {
    localStorage.setItem("workflowchecklistpagesize", pagination.pageSize);
    let field = sorter.field;
    let order = 0;
    if (sorter.order === "descend") {
      order = 1;
    }
    let param = {
      field: field,
      order: order,
      page: pagination.current,
      pagesize: pagination.pageSize,
      seltype: this.state.seltype,
      userid: currentUser.id,
      code: this.state.code,
      name: this.state.name,
      tablename: this.state.tablename,
    }
    this.fetch(param);
  };
  tabsClick = e => {
    let param = {
      page: 1,
      pagesize: this.state.pagesize,
      seltype: e.key,
      userid: currentUser.id,
      code: this.state.code,
      name: this.state.name,
      tablename: this.state.tablename,
    }
    this.fetch(param);
  };
  onDragEnter = info => {
    window.console.log(info);
  };
  handleCheck = (record, next_type) => {
    if (!currentUser.isAudit) {
      notification.error("没有权限.");
      return;
    }
    let item = {
      bill: record.bill_enum,
      billid: record.id,
      next_type: next_type,
      billtype: record.bill_type,
      message: "同意",
      userid: currentUser.id,
      billdate: moment().format('YYYY-MM-DD'),
      orgunitid: record.orgunitid,
    }
    Workflow.check(item).then(data => {
      if (data[0].flag === 0) {
        ///----------------------------------
        notification.success(data[0].message);
        let param = {
          page: this.state.page,
          pagesize: this.state.pagesize,
          seltype: this.state.seltype,
          userid: currentUser.id,
          code: this.state.code,
          name: this.state.name,
          tablename: this.state.tablename,
        }
        this.fetch(param);
      } else {
        notification.error(data[0].message);
      }
    })
      .catch(error => {
        notification.error(error.message, error.detailedMessage);
      });

    // let item = {
    //   bill: record.bill_enum,
    //   id: record.id,
    //   billtype:record.bill_type,
    //   next_type:next_type,
    //   message: "",
    //   status: record.billstatus,
    //   orgunitid:this.state.orgunitid,
    // }
    // CheckDialog.showModal({ bill_check: item })
    //   .onClose((result = {}) => {
    //     if (result.success) {
    //       let param = {
    //         page: this.state.page,
    //         pagesize: this.state.pagesize,
    //         seltype: this.state.seltype,
    //         userid: currentUser.id,
    //         code: this.state.code,
    //         name: this.state.name,
    //       }
    //       this.fetch(param);
    //     }
    //   }).onDismiss(() => {
    //   });
  };
  handleclear = () => {
    this.setState({
      code: "",
      name: "",
      tablename: "",
    });
  }
  handlefieldshow = () => {
    CreateQueryShowFieldDialog.showModal({ queryshowfield: this.state.queryshowfielddata })
      .onClose((result = {}) => {
        if (result.success) {
          this.fieldsshowload();
        }
      }).onDismiss(() => {
      });
  }
  render() {
    // const { currentPage } = this.state;
    const paginationProps = {
      showSizeChanger: true,
      // showQuickJumper: true,
      total: this.state.total, // 数据总数
      pageSize: parseInt(this.state.pagesize), // 每页条数
      current: parseInt(this.state.page), // 当前页码
      pageSizeOptions: ["10", "20", "30", "100"],
      showTotal: ((total) => {
        return `共 ${total} 条`;
      }),
    };
    let listcolumns = [];

    if (this.state.queryshowfielddata.fieldsshow !== undefined) {
      (this.state.queryshowfielddata.fieldsshow || []).map(item => {
        let items = this.state.queryshowfielddata.fieldsall.filter((p) => {
          return p.key === item;
        });
        if (items.length > 0) {
          listcolumns.push({
            title: items[0].title,
            dataIndex: item,
            key: item,
            sorter: (a, b) => a[item] > b[item] ? 1 : -1
          })
        }
        return item;
      }
      );
    }


    listcolumns.push({
      title: '操作',
      key: 'action',
      render: (record) => (
        <span>
          {(this.state.seltype === "1" && record.bill_enum === "employee" && record.bill_type === 0) && (
            <Button type="primary"> <Router history={customHistory}>
              <Link to={`/employee/new/${record.id}`} style={{ color: "white" }}>编辑</Link>
            </Router></Button>
          )}
          {(this.state.seltype === "1" && record.bill_enum === "employee" && record.bill_type === 1) && (
             <Button type="primary"><Router history={customHistory}>
              <Link to={`/employee/openseapool/new/${record.id}`} style={{ color: "white" }}>编辑</Link>
            </Router></Button>
          )}
          {(this.state.seltype === "1" && record.bill_enum === "project") && (
             <Button type="primary"><Router history={customHistory}>
              <Link to={`/project/new/${record.id}`} style={{ color: "white" }}>编辑</Link>
            </Router></Button>
          )}
          {(this.state.seltype === "1" && record.bill_enum === "payment" && record.bill_type === 0) && (
            <Button type="primary"><Router history={customHistory}>
              <Link to={`/payment/outnew/${record.id}/0`} style={{ color: "white" }}>编辑</Link>
            </Router></Button>
          )}
          {(this.state.seltype === "1" && record.bill_enum === "payment" && record.bill_type === 1) && (
            <Button type="primary"><Router history={customHistory}>
              <Link to={`/payment/innew/${record.id}/0`} style={{ color: "white" }}>编辑</Link>
            </Router></Button>
          )}
          <Divider type="vertical" />
          {(this.state.seltype === "1") && (
            <> <Button type="primary" onClick={() => this.handleCheck(record, 1)} >
              <i className="fa fa-check m-r-5" />
              {"审核"}</Button>
              <Divider type="vertical" />
              <Button type="primary" onClick={() => this.handleCheck(record, 2)} >
                <i className="fa fa-reply m-r-5" />
                {"驳回"}</Button></>
          )}
          {(this.state.seltype !== "1") && (
            <>{record.bill_enum === "employee" && (<b className="clickable" >
              {record.bill_type === 0 ? "私有池" : "公海池"}</b>)}
              {record.bill_enum !== "employee" && (<Divider type="vertical" />)}
              {record.bill_enum !== "employee" && (<Button type="primary" onClick={() => this.handleCheck(record, 3)} >
                <i className="fa fa-reply m-r-5" />
                {"取消审核"}</Button>)}
            </>
          )}
        </span>
      ),
    });
    return (
      <ConfigProvider locale={zhCN}>
        <div style={{ width: "400px", height: "60px" }}>
          <div style={{ width: "20px", height: "50px", float: "left" }}>
          </div>
          <div style={{ width: "50px", height: "50px", float: "left" }}>
            <img src="/static/images/employeelist.png" alt="HR" loading="lazy" />
          </div>
          <div style={{ width: "320px", height: "30px", float: "left" }}>
            <h3 style={{ margin: "7px", padding: "0" }}>{this.state.seltype === "1" ? "待我审核单据" : "我已经审核单据"}</h3>
          </div>
        </div>
        <Layout>
          <Layout style={{ padding: '0 24px 24px' }}>
            <Row style={{ marginBottom: 5 }}>
              {/* <Col span={2}><div style={{ marginTop: "5px", textAlign: "right", marginRight: "10px" }}>
                人员编码:</div></Col>
              <Col span={6}>
                <AutoComplete
                  style={{ width: "100%" }}
                  value={this.state.code}
                  onChange={value => {
                    localStorage.setItem("employeelistcode", value);
                    this.setState({ code: value });
                  }}
                  placeholder="人员编码"
                  filterOption={(inputValue, option) =>
                    option.value.indexOf(inputValue) !== -1}>
                </AutoComplete>
              </Col> */}
              <Col span={2}><div style={{ marginTop: "5px", textAlign: "right", marginRight: "10px" }}>
                单据类型:</div></Col>
              <Col span={6}>
                <AutoComplete
                  style={{ width: "100%" }}
                  value={this.state.tablename}
                  onChange={value => {
                    this.setState({ tablename: value });
                  }}
                  placeholder="单据类型"
                  filterOption={(inputValue, option) =>
                    option.value.indexOf(inputValue) !== -1}>
                    <AutoComplete.Option key={'人员信息'} value={'人员信息'}>{'人员信息'}</AutoComplete.Option>
                    <AutoComplete.Option key={'项目信息'} value={'项目信息'}>{'项目信息'}</AutoComplete.Option>
                    <AutoComplete.Option key={'收款信息'} value={'收款信息'}>{'收款信息'}</AutoComplete.Option>
                    <AutoComplete.Option key={'付款信息'} value={'付款信息'}>{'付款信息'}</AutoComplete.Option>
                </AutoComplete>
              </Col>
              <Col span={2}><div style={{ marginTop: "5px", textAlign: "right", marginRight: "10px" }}>
                人员名称:</div></Col>
              <Col span={6}>
                <AutoComplete
                  style={{ width: "100%" }}
                  value={this.state.name}
                  onChange={value => {
                    localStorage.setItem("employeelistname", value);
                    this.setState({ name: value });
                  }}
                  placeholder="人员名称"
                  filterOption={(inputValue, option) =>
                    option.value.indexOf(inputValue) !== -1}>
                </AutoComplete>
              </Col>
              <Col span={8}>
                <Divider type="vertical" />
                <Button type="primary" onClick={() => this.handlesel()} >
                  <i className="fa fa-search m-r-5" />
                  查询
                </Button>
                <Divider type="vertical" />
                <Button onClick={() => this.handleclear()} >
                  清空
                </Button>
                <Divider type="vertical" />
                <Button onClick={() => { this.setState({ showall: !this.state.showall }); }} >
                  {this.state.showall && (<UpOutlined />)}
                  {!this.state.showall && (<DownOutlined />)}
                  {this.state.showall ? '默认' : '更多'}
                </Button>
              </Col>
            </Row>
            <Row style={{ marginBottom: 5 }}>
              <Col span={10}>
                <Dropdown
                  trigger={["click"]}
                  overlay={
                    <Menu>
                      {currentUser.hasPermission("fieldshow") && (
                        <Menu.Item key="delete-item">
                          <a onMouseUp={() => this.handlefieldshow()}>显示隐藏列</a>
                        </Menu.Item>
                      )}
                    </Menu>
                  }>
                  <Button type="primary" style={{ margin: "10px" }} data-test="CreateButton" >
                    <AppstoreFilled />更多功能
                  </Button>
                </Dropdown>
              </Col>
            </Row>
            <Menu onClick={this.tabsClick} selectedKeys={this.state.seltype} mode="horizontal">
              <Menu.Item key="1">{"待我审核单据"}</Menu.Item>
              <Menu.Item key="2">{"我已经审核单据"}</Menu.Item>
            </Menu>
            <div>
              <Table rowKey='rowid'
                columns={listcolumns}
                dataSource={this.state.data}
                pagination={paginationProps}
                loading={this.state.loading}
                onChange={this.handleTableChange}
              />
            </div>
          </Layout>
        </Layout>
      </ConfigProvider>);
  }
}

routes.register(
  "Workflow.Billcheck",
  routeWithUserSession({
    path: "/workflow/billcheck",
    title: "待我审核的单据",
    render: pageProps => <WorkFlowCheckList {...pageProps} seltype="1" />,
  })
);
routes.register(
  "Workflow.Billcheck1",
  routeWithUserSession({
    path: "/workflow/billcheck/ok",
    title: "已审核的单据",
    render: pageProps => <WorkFlowCheckList {...pageProps} seltype="2" />,
  })
);
